<template>
  <div style="height:100%;">
     <mapBoxViewer 
     ref="refMap" 
      @onInit="initMap"
      @onDrag="openPupop"
      @onDragEnd="openPupop"
      @onZoom="onChangeZoom"
      @onZoomEnd="onChangeZoom" />
  </div>
</template>

<script setup>
import {ref,onMounted,watch } from "vue"
import mapBoxViewer from "@/components/mapBox/index.vue";
import {getLandMiniList,getFarmLandCount} from '@/api/gis'
import { getCookie } from '@/utils/httpParamsHandler';
import {getPageList} from '@/utils/common'
const props = defineProps({
  landInfo:{
    type:Object,
    default:{}
  },
  plantingPlanId:{
    type:String,
    default:''
  },
  selectLandList:{
    type:Array,
    default:[]
  },
  bottomList:{
    type:Array,
    default:[]
  }
})

const emit = defineEmits(['onClick','complete'])
let mapView = null
let farmLandId=null
const dataList = ref([])
const refMap = ref(null)
const landInfoData = ref({})

watch(()=>props.plantingPlanId,()=>{
  if(props.plantingPlanId){
    updateData()
  }
})
watch(()=>props.selectLandList,()=>{
    if(mapView){
        updateData()
    }
})
onMounted(()=>{
})

const initMap =async (map)=>{
   mapView = map
   const res = await getFarmLandCount({companyId:getCookie('companyId'),farmId:getCookie('farmId')})
   if(res.success){
      let pages =getPageList(res.data?.farmLandCount||6000)
      let params ={
        farmId:getCookie('farmId'),
        companyId:getCookie('companyId')
      }
      pages.forEach(async (item)=>{
          window.setTimeout(async () => {
              let res =await getLandMiniList({...params,...item})
              if(res?.success){
                  dataList.value =dataList.value.concat(res.data.filter((item)=>item.geom!=null))
                  if(pages.length==item.page){
                     emit('complete',dataList.value)
                  }
                  if(item.page==1){
                      addLandList()
                  }else{
                  updateData()
                  }
              }
              }, item.page==1?0:(item.page*200));
      })
   }
}


const updateData =()=>{
    let filterList =dataList.value.filter((item)=>item.plantingPlanId == props.plantingPlanId).map((item)=> {
        if(item?.geom && item.geom!='null' && item.geom !=null){
            let growthColor = props.selectLandList.find((m)=>m.farmLandId==item.farmLandId)?.growthColor //||'#25c289'
            return {
                type: 'Feature',
                id:item.farmLandId,
                properties: {
                    description: item.farmLandName+'\n'+Number(item.mapAreaSize||0).toFixed(2)+'亩',
                    lineColor:growthColor||'#25c289',//'#25c289',
                    lineWidth:2,
                    opacity:growthColor?1:0,
                    ...item
                },
                geometry: {
                    type: 'Polygon',
                    coordinates: [JSON.parse(item.geom||'[]')]
                }
            }
        }
    })
    if(mapView){
       window.setTimeout(() => {
         mapView.getSource('polygons-source')?.setData({type: 'FeatureCollection', features:filterList})
      }, 200);
    }
    let list= dataList.value.filter((item)=>props.selectLandList.map((m)=>m.farmLandId).includes(item.farmLandId))
    let centerList =[]
    list.forEach((item)=>{
        centerList.push([Number(item.locationLongitude),Number(item.locationLatitude)])
    })
    refMap.value.locationCenter(centerList)
}

const addSourceData =()=>{
         mapView.addSource('polygons-source', {
            type: 'geojson',
            data: {
                type: 'FeatureCollection',
                features: dataList.value.map((item)=> {
                  if(item?.geom && item.geom!='null' && item.geom !=null){
                    return {
                        type: 'Feature',
                        id:item.farmLandId,
                        properties: {
                            description: item.farmLandName+'\n'+Number(item.mapAreaSize||0).toFixed(2)+'亩',
                            lineColor:'#25c289',
                            lineWidth:1,
                            opacity:0,
                            ...item
                        },
                        geometry: {
                            type: 'Polygon',
                            coordinates: [JSON.parse(item.geom||'[]')]
                        }
                    }
                  }
                })
            }
    })
}


const addLandList =()=>{
     addSourceData()
     //添加线条
     mapView.addLayer({
          'id': 'polygons-layer-line',
          'type': 'line',
          'source': 'polygons-source',
          'layout': {},
          'paint': {
              'line-color': ['get', 'lineColor'],
              'line-width': ['get', 'lineWidth']
          }
  })

  // 添加多边形图层-图层
  mapView.addLayer({
          'id': 'polygons-layer-fill',
          'type': 'fill',
          'source': 'polygons-source',
          'paint': { 
            'fill-opacity': ['get', 'opacity'],
            'fill-color':['get', 'lineColor'],
            },
            "interactive": true
      })

      // 添加多边形图层-文字
      mapView.addLayer({
          'id': 'polygons-layer-text',
          'type': 'symbol',
          'source': 'polygons-source',
          layout: {
              'text-field': ['get', 'description'],
              'text-size': 12,
              'text-anchor': 'center',
              'visibility': 'none',
              'text-offset': [0, 1.5],
          },
          paint: {
              'text-color': '#ffffff'
          },
          metadata: {
              'renderedOnServer': false
          }
      });
  

   mapView.on('click','polygons-layer-fill',(e)=> {
      let item = e.features[0]
      landInfoData.value = {
        ...item?.properties,
        longitude:item?.properties?.locationLongitude,
        latitude:item?.properties?.locationLatitude
      }
      changeLandColors(item.id)
      emit('onClick',item.properties)

    })
}

const changeLandColors =(Id)=>{
  if(farmLandId){
          mapView.setFeatureState({source: 'polygons-source', id:farmLandId },{ click: false });
      }
    farmLandId=Id
    mapView.setFeatureState({source: 'polygons-source', id: Id },{ click: true });
}

const onChangeZoom =(row)=>{
  if(row.currentZoom<17){
    mapView.setLayoutProperty('polygons-layer-text', 'visibility', 'none');
  }else{
    mapView.setLayoutProperty('polygons-layer-text', 'visibility', 'visible');
  }
}

</script>

<style lang="scss" scoped>

</style>